package com.tian.service.impl;

import com.alibaba.fastjson.JSON;
import com.tian.config.SystemMessageTemplate;
import com.tian.config.SystemMessageTemplateLoader;
import com.tian.entity.ChargeSystemMessage;
import com.tian.entity.ChargeSystemMessageContent;
import com.tian.mapper.ChargeSystemMessageContentMapper;
import com.tian.mapper.ChargeSystemMessageMapper;
import com.tian.message.ChargeSystemMessageSendMessage;
import com.tian.service.ChargeSystemMessageMQService;
import com.tian.util.ChargeMarketRedisKeyPrefix;
import com.tian.util.ConstantsUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-12 11:39
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class ChargeSystemMessageMQServiceImpl implements ChargeSystemMessageMQService {
//    @Resource
//    private SystemMessageTemplateLoader systemMessageTemplateLoader;
    @Resource
    private ChargeSystemMessageContentMapper chargeSystemMessageContentMapper;
    @Resource
    private ChargeSystemMessageMapper chargeSystemMessageMapper;
    @Resource
    private RedissonClient redissonClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(ChargeSystemMessageSendMessage chargeSystemMessageSendMessage) {
        //采用redis防重，避免重复发送
        //reqId=日期+用户id+模板id
        RBucket<String> bucket = redissonClient.getBucket(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_DUPLICATE_KEY + chargeSystemMessageSendMessage.getReqId());
        if (bucket.isExists()) {
            log.error("消息重复发送,ReqId={}", chargeSystemMessageSendMessage.getReqId());
            return Boolean.TRUE;
        }
        //设置有效期(1 天)
        bucket.set(chargeSystemMessageSendMessage.getReqId(), ConstantsUtil.MESSAGE_DUPLICATION_TIME, TimeUnit.DAYS);

//        SystemMessageTemplate systemMessageTemplate = systemMessageTemplateLoader.getTemplates().get(chargeSystemMessageSendMessage.getTemplateId());
//        if (systemMessageTemplate == null) {
//            log.error("消息模板不存在");
//            return false;
//        }

//        String body = getMessageBody(systemMessageTemplate, chargeSystemMessageSendMessage.getParams());
//
//        ChargeSystemMessageContent chargeSystemMessageContent = new ChargeSystemMessageContent();
//        chargeSystemMessageContent.setContent(body);
//        chargeSystemMessageContent.setTitle(systemMessageTemplate.getTitle());
//        chargeSystemMessageContentMapper.insert(chargeSystemMessageContent);
//
//        ChargeSystemMessage chargeSystemMessage = new ChargeSystemMessage();
//        chargeSystemMessage.setUserId(chargeSystemMessageSendMessage.getUserId());
//        chargeSystemMessage.setMessageId(chargeSystemMessageContent.getId());
//        chargeSystemMessage.setIsRead(0);
//        chargeSystemMessage.setSendTime(new Date());
//        chargeSystemMessageMapper.insert(chargeSystemMessage);

//        setCache(chargeSystemMessageSendMessage.getUserId(), chargeSystemMessageContent, chargeSystemMessage);

        return Boolean.TRUE;
    }

    private void setCache(Long userId, ChargeSystemMessageContent chargeSystemMessageContent, ChargeSystemMessage chargeSystemMessage) {
        redissonClient.getBucket(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_CONTENT_ID_KEY + chargeSystemMessageContent.getId()).set(JSON.toJSON(chargeSystemMessageContent));

        RList<Long> list = redissonClient.getList(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_LIST_KEY + userId);
        list.add(chargeSystemMessage.getId());

        RMap<Long, String> map = redissonClient.getMap(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_MAP_KEY + userId);
        map.put(chargeSystemMessage.getId(), JSON.toJSONString(chargeSystemMessage));

        //只保留3个月时间内的站内信，在启动一个定时任务
        RScoredSortedSet<String> scoredSortedSet = redissonClient.getScoredSortedSet(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_SET_KEY);
        setExpiredDate(chargeSystemMessage, scoredSortedSet);
    }

    private void setExpiredDate(ChargeSystemMessage chargeSystemMessage, RScoredSortedSet<String> scoredSortedSet) {
        LocalDateTime expiredDateTime = chargeSystemMessage.getSendTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime()
                .plusMonths(3);  // 添加 3 个月
        Date expired = Date.from(expiredDateTime.atZone(ZoneId.systemDefault()).toInstant());
        String value = chargeSystemMessage.getId() + ConstantsUtil.SET_MESSAGE_SPLIT + expired + ConstantsUtil.SET_MESSAGE_SPLIT + chargeSystemMessage.getUserId();
        scoredSortedSet.add(expired.getTime(), value);
    }

//    public String getMessageBody(SystemMessageTemplate systemMessageTemplate, Map<String, String> replacements) {
//        String body = systemMessageTemplate.getContent();
//        for (Map.Entry<String, String> entry : replacements.entrySet()) {
//            body = body.replace("${" + entry.getKey() + "}", entry.getValue());
//        }
//        return body;
//    }
}
